<?php

namespace App\Service\Impl;

if (!defined('IN_PX'))
    exit;

use App\Service\Member;
use App\Repository;
use App\Tools\Auxi;
use App\Tools\Html;
use Phoenix\Http\RequestMethod;
use Phoenix\Support\MsgHelper;

/**
 * 用户表服务类
 * v1.0.0 开发了登录注册完善信息修改忘记密码功能
 */
class MemberImpl implements Member {

    const VERSION = '1.0.0';

    //服务层组件
    private function __Service($value = 'member') {}

    private function __Value($__PACKAGE__, $__ROOT__, $__RM__, $setting, $cfg, $__LANGUAGE_ID__) {}

    private function __Inject($session, $cache, Repository\Member $repoMem, Repository\User $repoUser) {}

    public function memberLogin($post) {
        if (isset($post['name']) && $post['name'] != '') {
            //用户名和手机号均可
            $_rs = $this->repoMem->findMember($post['name'], 0);
        } else {
            return MsgHelper::err(11001);
        }
        if (!$_rs) {
            return MsgHelper::err(11002);
        } elseif ($_rs->is_status == 0) {
            return MsgHelper::err(11003);      //     该账号已被冻结!
        }
        if (strcmp($_rs->password, md5($post['password'] . $_rs->guid)) == 0) { //比对密码
            $_time = time();
            $_aryUpdateRow = array(
                'last_log_date' => '?'
            );
            $_aryUpdateBind = array(
                $_time,
                $_rs->member_id
            );
            $this->repoMem->update($_aryUpdateRow, $_aryUpdateBind);
            $this->session->user = array(
                'memberId' => $_rs->member_id,
                'realName' => $_rs->real_name,
                'mobile' => $_rs->mobile
            );
            return MsgHelper::err(0);
        } else {
            return MsgHelper::err(11004);
        }
    }

    public function register($post) {
        Auxi::checkMustFieldT(array('mobile', 'mobileCode', 'pwd', 'rePwd'), $post);

            if ($post['pwd'] != $post['rePwd']) {
                return MsgHelper::err(20002);

            }
            $_void = $this->ckValidCode(0, $post);//验证手机验证码
            if ($_void) {
                if ($_void !== true) {
                    return $_void;
                }
                $post['mobile'] = trim($post['mobile']);
            } else {
                return MsgHelper::err(20003);
            }

            $_time = time();
            $data['guid'] = Auxi::guid();
            $data['password'] = md5(trim($post['pwd']) . $post['guid']);
            $data['reg_time'] = $data['last_log_date'] = $data['update_time'] = $_time;
            $data['real_name'] = trim($post['name']);
            $data['company'] = trim($post['company']);
            $data['mobile'] = trim($post['mobile']);
            $data['is_status'] = 1;
            if ($_identity = $this->repoUser->add($data)) {
                //清除注册验证码
                $this->distroyCacheCode(0, $post);
                $this->session->user = array(
                    'memberId' => $_identity,
                    'realName' => $data['real_name'],
                    'mobile' => $data['mobile']
                );
                return MsgHelper::err(0, '注册成功!');
            } else {
                return MsgHelper::err(20009);
            }
    }

    private function ckValidCode($type, $post) {
        if (isset($post['mobile']) && Auxi::isValidMobile(trim($post['mobile'])) && isset($post['mobileCode'])) {
            //注册用户 获取缓存中的验证码

            //查找用户
            $count = $this->repoUser->findMemberNum(trim($post['mobile']), 'mobile');

            if ($type == 0) {
                //用户注册
                $cacheName = 'registeMemberCode_';
                if ($count > 0) {
                    return MsgHelper::err(20000, '该手机号已被注册!');die;
                }
            } else if ($type == 1) {
                //快速登录
                $cacheName = 'SoonLoginCode_';
                if ($count == 0) {
                    return MsgHelper::err(20000, '该手机号暂未注册!');
                }
            } else if ($type == 2) {
                //忘记密码
                $cacheName = 'forgetLoginCode_';
                if ($count == 0) {
                    return MsgHelper::err(20000, '该手机号暂未注册!');
                }
            }
            $_cacheCode = $this->cache->expires($this->_expire * 600)->get($cacheName . $post['mobile']);
            if ($_cacheCode && ($post['mobileCode'] == substr($_cacheCode, 0, 6))) {
                //销毁缓存
                return true;
            }
        }
        return false;
    }

    /**
     * @Title: distroyCacheCode
     * @param $type
     * @Description: TODO 销毁缓存
     */
    private function distroyCacheCode($type, $post) {
        if ($type == 0) {
            //用户注册
            $cacheName = 'registeMemberCode_';
        } else if ($type == 1) {
            //快速登录
            $cacheName = 'SoonLoginCode_';
        } else if ($type == 2) {
            //忘记密码
            $cacheName = 'forgetLoginCode_';
        }
        $this->cache->delete($cacheName . $post['mobile']);
    }

    public function perfect($post) {
        $userInfo = $this->session->member;
        $result = $this->repoMem->findMember($userInfo['member_id'], 1);
        if ($userInfo) {
            $memberName = isset($post['membername']) ? Html::getTextToHtml($post['membername']) : trim($result->member_name);
            $mobile = isset($post['mobile']) ? trim($post['mobile']) : trim($result->mobile);
            $sex = isset($post['sex']) ? trim($post['sex']) : trim($result->sex);
            $location = isset($post['location']) ? Html::getTextToHtml(trim($post['location'])) : trim($result->location);
            $department = isset($post['department']) ? intval($post['department']) : intval($result->department_id);
            $post1 = array(
                'member_name' => $memberName,
                'mobile' => $mobile,
                'sex' => $sex,
                'location' => $location,
                'department_id' => $department,
                'release_date' => time(),
                'member_id' => $userInfo['member_id'],
            );
            $arr1 = array(
                '`member_name`' => '?',
                '`mobile`' => '?',
                '`sex`' => '?',
                '`location`' => '?',
                '`department_id`' => '?',
                '`release_date`' => '?'
            );
            $return = $this->repoMem->update($arr1, $post1);
            if ($return) {
                return 0;
            } else {
                return 11009;       //修改失败
            }
        } else {
            return 11009;       //修改失败
        }
    }

    public function addOpenid($post) {
        $post['mobile'] = trim($post['mobile']);
        $post['code'] = trim($post['code']);
        $openid = $this->session->openid;

        if (!$openid || empty($openid['openid'])) {
            return 11025;       //  请先授权登录
        }


        if (!Auxi::isValidMobile($post['mobile']) || empty($post['mobile'])) {
            return 11005;       //  请输入正确手机号
        }

        $post['openid'] = isset($openid['openid']) ? $openid['openid'] : '';
        $post['nickname'] = isset($openid['nickname']) ? trim($openid['nickname']) : '';
        $post['headimgurl'] = isset($openid['headimgurl']) ? trim($openid['headimgurl']) : '';
        $post['member_name'] = $post['nickname'];
        $post['portrait'] = $post['headimgurl'];
        $post['location'] = isset($post['location']) ? Html::getTextToHtml($post['location']) : '';
        $post['sex'] = isset($post['sex']) ? intval($post['sex']) : 0;
        $post['department_id'] = isset($post['department']) ? intval($post['department']) : 0;

        $_time = time();
        $post['guid'] = Auxi::guid();
        $post['password'] = substr($post['mobile'], -6, 6);
        $post['password'] = md5($post['password'] . $post['guid']);
        $post['add_date'] = $post['last_log_date'] = $post['release_date'] = $_time;
        $post['last_log_ip'] = ip2long(Auxi::getIP());
        $post['is_status'] = 1;

        if (!($this->repoMem->chkExists2($post['mobile']))) {
            if (!($this->repoMem->chkExists($post['mobile']))) {
                if (($_identity = $this->repoMem->save($post))) {
                    $this->destoryOpenid($_identity);
                    return 0;
                } else {
                    return 11007;       //  注册失败
                }
            } else {
                $_rs = $this->repoMem->findMember($post['mobile']);
                $_aryUpdateRow = array(
                    '`openid`' => '?',
                    '`nickname`' => '?',
                    '`headimgurl`' => '?',
                );
                $_aryUpdateBind = array(
                    $openid['openid'],
                    $openid['nickname'],
                    $openid['headimgurl'],
                    $_rs->member_id
                );
                $_return = $this->repoMem->update($_aryUpdateRow, $_aryUpdateBind);

                if ($_return) {
                    $this->destoryOpenid($_rs->member_id);
                    return 11023;           //   绑定成功
                } else {
                    return 11024;           //   绑定失败
                }
            }
        } else {
            $_rs = $this->repoMem->findMemberOpenid($post['mobile'], $openid['openid']);
            if (count($_rs) > 0) {
                $this->destoryOpenid($_rs->member_id);
                return 11021;       // 绑定成功,直接进入会员中心!
            } else {
                return 11022;       // 该手机号已经被绑定~
            }
        }
    }

    public function destoryOpenid($memberid) {
        $this->session->destory('openid');
        $this->session->member = array(
            'member_id' => $memberid,
        );
        return true;
    }

    public function logout() {
        $this->session->destory('member');
        if (!$this->session->member) {
            return 0;
        } else {
            return 11010;       //   退出失败
        }
    }

    public function modifyPassword($post) {
        $userInfo = $this->session->member;
        if ($_rs = $this->repoMem->findMember($userInfo['member_id'], 1)) {
            if (!($_rs->password == md5($post['passwordOld'] . $_rs->guid))) {
                return 11011;
            }
        }
        $post['password'] = trim($post['password']);
        if ($post['password'] != trim($post['passwordRep'])) {
            return 11012;
        } else {
            $rs = $this->password($post['password'], $userInfo['member_id']);
            if ($rs == 0) {
                return 0;
            } else {
                return 11009;       //修改失败
            }
        }
    }

    public function uploadPassword($post) {
        $post['password'] = trim($post['password']);
        $post['passwordRep'] = trim($post['passwordRep']);
        $post['mobile'] = trim($post['mobile']);
        if (!Auxi::isValidMobile($post['mobile']) || empty($post['mobile'])) {
            return 11005;       //  请输入正确手机号
        }

        if (!$infoDetail = $this->repoMem->findMember($post['mobile'], 0)) {
            return 11002;       //   该用户名或手机号未在本网站注册过
        }
        
        if ($post['password'] != trim($post['passwordRep'])) {
            return 11012;
        } else {
            $rs = $this->password($post['password'], $infoDetail->member_id);
            if ($rs == 0) {
                return 0;
            } else {
                return 11009;       //修改失败
            }
        }
    }

    // 公共执行修改密码接口
    public function password($password, $memberid) {
        $guid = Auxi::guid();
        $password = md5($password . $guid);
        $post1 = array(
            'guid' => $guid,
            'password' => $password,
            'release_date' => time(),
            'member_id' => $memberid,
        );
        $arr1 = array(
            '`guid`' => '?',
            '`password`' => '?',
            '`release_date`' => '?'
        );
        if ($return = $this->repoMem->update($arr1, $post1)) {
            return 0;
        } else {
            return 11009;       //修改失败
        }
    }
}
